<?php
// inizializzazione
error_reporting( E_ALL );
define ( 'ALL', 'ALL' );
//---------- Configurazione


class Logger
{
	//config
	var $logErrors = false; //don't activate as interferes with main class errorhandler	
	var $enabled= true;
	var $_printScreen = false;
	var $_progressiveFlush = true; //if true every line printed on screen will be flushed
	
	// runtime
	var $content = '';
	var $_registered = false;
	var $_mail = null;
	
	function printScreen ( $active  )
	{
		$me =& Logger::_getInstance();
		$me->_printScreen = !! $active;
	}
	function progressiveFlush ( $active = null  )
	{
		$me =& Logger::_getInstance();
		if ( $active === true || $active === false ) $me->_progressiveFlush = !! $active;
		return $me->_progressiveFlush;
	}
	function &_getInstance ()
	{
		static $instance;
		if ( ! $instance )
		{
			$class = __CLASS__;
			$instance = new $class();
		}
         		return $instance;
	}
	function registerMe ()
	{
		$me =& Logger::_getInstance();
		if ( !$me->_registered )
		{
			$me->_registered = true;
			register_shutdown_function( array( 'Logger', 'shutdownOperations' ));
			if ( $me->logErrors )
			{
				if ( version_compare("4.0.4", "5.0", "<") )
				{
					if ( set_error_handler( array( 'Logger', 'logError') ));
				} else {
					if ( set_error_handler( array( 'Logger', 'logError'), E_ALL ));
				}
			}
		}
	}
	function logError( $errno, $errstr, $errfile, $errline )
	{
		if ( $errno > E_ALL ) return false;
		$me =& Logger::_getInstance();
		 $me->log ("$errstr in $errfile on line $errline");
		 return false;
	}
	function nonScalar2String ( $nonScalar )
	{
		if ( is_object( $nonScalar )) return print_r( $nonScalar, true );
		if ( is_array ( $nonScalar )) return print_r( $nonScalar, true );
		return $nonScalar;
	}
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $message
	 * @param  mixed $dump (optional) variable to be dumped in the lpg
	 */
	function log ( $message )
	{
		$me =& Logger::_getInstance();
		if ( ! $me->enabled ) return false;
		$me->registerMe();
		
		if ( func_num_args() == 2 )
		{
			$dump = func_get_arg( 1 );
			$message = $message."\n".$me->nonScalar2String( $dump );
		}
		
		$decoratedMessage = date( 'Y-d-m H:i:s')." - $message \n";
		$me->content .= $decoratedMessage;
		if ( $me->_printScreen )
		{
			$me->toScreen( $decoratedMessage);
			if ( $me->progressiveFlush() ) flush();
		}
	}
	function toScreen ( $message )
	{
		$message = str_replace( ' ', '&nbsp;', $message);
		echo nl2br( $message );
	}
	function setMail ( $mail )
	{
		if ( !$mail )
		{
			trigger_error( '$mail is empty', E_USER_NOTICE );
			return false;
		}
		$me =& Logger::_getInstance();
		$me->_mail = $mail;
	}
	function shutdownOperations ()
	{
		$me =& Logger::_getInstance();
		if ( $me->_mail )
		{
			error_log( $me->content, 1, $me->_mail );
		}
	}
}

if ( ! function_exists( 'lll' ))
{
	function lll ( $message )
	{
		$args = func_get_args();
		return call_user_func_array( array( 'Logger', 'log' ), $args );
	}
}
?>